/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 07 - 05
 * Time: 9:50
 */
class Solution1 {
    public String truncateSentence(String s, int k) {
        StringBuilder stringbuilder = new StringBuilder();
       String[] str = s.split(" ");
       for(int i = 0; i < k; i++) {
           stringbuilder.append(str[i]);
           if(i < k - 1) {
              stringbuilder.append(" ");
           }
       }
       return stringbuilder.toString();
    }
}

//示例代码
class Solution2 {
    public String truncateSentence(String s, int k) {
        int n=s.length();
        int end=0, count=0;
        for(int i=1;i<=n;i++){
            if(i==n || s.charAt(i)==' '){
                count++;
                if(count==k){
                    end=i;
                    break;
                }
            }
        }
        return s.substring(0, end);
    }
}



